import { useEffect, useMemo, useRef } from 'react';
import { setPrinterName, getCurrentUser } from '@/utils/authority';
import { loadScript } from '@/utils/utils.jsx';
import PrintQuenue from './PrintQuenue';

/**
 * @param {number} threshold - 更新阈值
 * @param {boolean} needUpdatePrintState - 是否需要更新打印状态
 * @param {boolean} needRecordBatch - 是否需要记录打印批次
 * @param {function} handleUpdateRender - 更新渲染逻辑，真值即代表需要更新页面
 * @returns {function}
 */
export const useKmPrintUniqCode = ({ threshold = 3, handleUpdateRender }) => {

  const printQueen = useRef(undefined); //打印队列
  const uniqueCodeArr = useRef([]); //已执行打印的唯一码

  //打印的公用参数
  const commonParams = useMemo(() => {
    return {
      el: '#kuaimaiIframePrint',
      appId: '1666316938957',
      itemsId: '69',
      userId: getCurrentUser()?.id + '',
    };
  }, []);

  //校验
  useEffect(() => {
    checkIsReady();
  }, [])

  //初始化快麦实例
  const checkIsReady = async () => {
    if (!window.KM_Template) {
      await loadScript('https://label-open.kuaimai.com/sdk/KM_Template.umd.js');
    }
    if (!window.KMTEMPLATE) {
      window.KMTEMPLATE = new KM_Template();
    }
    initMyQueueFunc();
  }

  //初始化队列实例
  const initMyQueueFunc = () => {
    if (!printQueen.current) {
      printQueen.current = new PrintQuenue(printExecFunc)
    }
  }

  //打印执行体
  function printExecFunc(val, next, isLast) {
    KMTEMPLATE.printBatch({
      ...commonParams,
      usbList: [val.printer],
      labelData: [val],
      callback: (res) => {
        next();
        const { uniqueCode } = val;
        if (res?.type == 'success' && uniqueCode) {
          uniqueCodeArr.current.push(uniqueCode);
          checkShouldUpdate(isLast);
        }
      }
    })
  }

  //根据阈值或最后一次，看是否更新打印状态和更新页面
  const checkShouldUpdate = (isLast) => {//true为最后一次 为强制性更新
    const codeArr = uniqueCodeArr.current;
    if (isLast || codeArr.length >= threshold) {
      uniqueCodeArr.current = [];
      handleUpdateRender?.(codeArr);
    }
  }

  //往队列推送打印数据
  const handlePushPrintData = (printData, printer) => {
    if (!printData?.length) {
      throw new Error('推送打印数据为空');
    }
    //1.更新打印机
    setPrinterName(printer);
    //2.推送打印
    const formatedData = formatInterfaceData(printData, printer);
    printQueen.current.add(formatedData);
  }

  //处理接口返回的数据
  const formatInterfaceData = (printData, printer) => {
    return printData.map(item => ({
      printer,
      id: item.kmTemplateId,
      data: item,
      uniqueCode: item?.zjf_pick_label[0]?.uniqueCode,
    }))
  }

  return {
    handlePushPrintData,
  };
}